package com.atguigu.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.atguigu.order.bean.Order;
import com.atguigu.order.service.OrderService;
import com.atguigu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public Order createOrder(Long productId, Long userId){
        Product product = getProductFromRemote(productId);

        Order order = new Order();

        order.setId(1L);
        //TODO 总金额
        BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(product.getNum()));
        order.setTotalAmount(totalAmount);
        order.setUserId(userId);
        order.setNickName("奈费勒");
        order.setAddress("苗圃");
        //TODO 远程查询商品列表
        order.setProducts(Arrays.asList(product));

        return order;
    }

    private Product getProductFromRemote(Long productId){
//        //1、获得商品服务所在的所有机器的IP和port（端口）
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//
//        ServiceInstance instance = instances.get(0);
//
//        //远程url
//        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
//        log.info("远程请求：{}",url);
//        System.out.println(url);
//


        String url = "http://service-product/product/"+productId;//restTemplate加了注解之后，会自动将service-product替换成地址
        //2、给远程发送请求
//        RestTemplate restTemplate = new RestTemplate();
        Product product = restTemplate.getForObject(url,Product.class);
        return product;
    }
}
